package controllers

import (
	"encoding/json"
	//	"errors"
	"qysoft/libs/encrypt"
	"qysoft/libs/seaweed"
	"qysoft/models"
	//	"reflect"
	"strconv"
	// "strings"
	"time"
	//	"github.com/astaxie/beego/httplib"

	"github.com/astaxie/beego"
)

//oprations for Livechannel
type LivechannelController struct {
	CommonController
}

func (c *LivechannelController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("DeleteLiveChannels", c.DeleteLiveChannels)
	c.Mapping("GetLiveUserByLive", c.GetLiveUserByLive)
	c.Mapping("GetLiveList", c.GetLiveList)
	c.Mapping("LiveList", c.LiveList)

}

// Livedata 前端post json数据
type Livedata struct {
	Scope        int
	Url          string
	Id           string
	Isdelete     int
	Organization string
	Type         int
	Status       int
	Users        []string
	Dept         string
	Vhost        string
	Stream       string
	Remark       string
	Title        string
}

// @Title Post
// @Description create Livechannel
// @Param	body		body 	models.Livechannel	true		"body for Livechannel content"
// @Success 201 {int} models.Livechannel
// @Failure 403 body is empty
// @router / [post]
func (c *LivechannelController) Post() {
	user := c.User
	var l Livedata
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &l)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrInputData)
	}

	if sum, _, _ := models.GetLiveChannelListByStream(l.Stream); sum > 0 {
		c.RetError(ErrDupChanel)
	}
	var v models.Livechannel
	//	org, err := models.GetOrganizationById(user.Organization.Id)
	// if err != nil {
	// 	c.RetError(ErrNoUser)
	// }
	v.Dept = user.Dept[0]
	v.Organization = user.Organization
	v.OrgName = user.Organization.Name
	//	范围
	v.Scope = l.Scope
	v.Vhost = l.Vhost

	// v.Status  = l.Status
	v.Title = l.Title
	v.Stream = l.Stream
	v.Url = v.Vhost + "/" + v.Stream
	v.Clicks = 0
	v.Status = 1
	v.Isdelete = 0
	fid, _, err := seaweed.SetFile("imgs/times.jpg")
	if err != nil {
		c.RetError(ErrFds)
	}
	v.Img = fid
	v.Remark = l.Remark
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	//是否录制

	v.Type = l.Type
	v.Id = encrypt.GetGuid()
	//	//	设置SRS录制
	//	enableSrc := "http://" + beego.AppConfig.String("StreadmAddress") +
	//		":1985/api/v1/raw?rpc=update&scope=dvr&value=__defaultVhost__" +
	//		"&param=enable&data=" + v.Url
	//	disableSrc := "http://" + beego.AppConfig.String("StreadmAddress") +
	//		":1985/api/v1/raw?rpc=update&scope=dvr&value=__defaultVhost__" +
	//		"&param=disable&data=" + v.Url
	//	//默认不录制
	//	req := httplib.Get(disableSrc)
	//	if v.Type == 1 {
	//		req = httplib.Get(enableSrc)
	//	}
	//	result := new(map[string]interface{})
	//	_, err = req.Response()
	//	if err != nil {
	//		c.RetError(ErrWriteFile)
	//	}
	//	req.ToJSON(&result)
	//	beego.Debug("/api/v1/raw?rpc=update:", result, err)
	_, err = models.AddLivechannel(&v)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrDatabase)
	}
	if v.Scope == 3 {
		// users := strings.Split(sdata["users"].(string), ",")
		for _, e := range l.Users {
			// uid, _ := strconv.ParseInt(e, 10, 64)
			models.AddUserLive(e, v.Id)
			c.Dlog("添加了直播用户授权，id：", v.Id)
		}
	}
	c.Dlog("添加了直播频道", v.Id)

	c.RetSuccess(v.Id)
}

// @Title Get
// @Description get Livechannel by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Livechannel
// @Failure 403 :id is empty
// @router /GetOne/:id [get]
func (c *LivechannelController) GetOne() {
	id := c.GetString(":id")
	v, err := models.GetLivechannelById(id)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// @Title Get All
// @Description get Livechannel
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Livechannel
// @Failure 403
// @router /GetAll [Post]
func (c *LivechannelController) GetAll() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var fields []string
	var sortby []string
	var order []string
	query := make(map[string]interface{})
	var limit int64 = -1
	var offset int64 = 0
	sortby = append(sortby, "id")
	order = append(order, "asc")
	sdata, _ := rdata.(map[string]interface{})
	query["Isdelete"] = "0"
	//用户角色不是系统管理员的筛选单位
	switch user.Role[0].Type {
	case 2:
		query["Organization__Id"] = user.Organization.Id
	case 3:
		ids := models.GetDeptChildrenStr(user.Dept[0].Id)
		query["Dept__Id__in"] = *ids
	}
	ipage, _ := sdata["page"].(string)
	page, _ := strconv.ParseInt(ipage, 10, 64)
	ipagesize, _ := sdata["pagesize"].(string)
	pagesize, _ := strconv.ParseInt(ipagesize, 10, 64)
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * pagesize
	}
	limit = pagesize

	l, count, err := models.GetAllLivechannel(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrNoData)
	}
	tabledata := make(map[string]interface{})
	tabledata["total"] = count
	tabledata["tabledata"] = l
	c.RetSuccess(tabledata)
}

// @Title Update
// @Description update the Livechannel
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Livechannel	true		"body for Livechannel content"
// @Success 200 {object} models.Livechannel
// @Failure 403 :id is not int
// @router /Update [post]
func (c *LivechannelController) Update() {
	user := c.User
	var ldata Livedata
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &ldata)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrInputData)
	}
	// rdata, err := c.AesDecode(c.GetString("tdata"))
	// if err != nil {
	// 	c.RetError(ErrToken)
	// }
	// sdata, _ := rdata.(map[string]interface{})
	// beego.Error(Ldata)
	// id := sdata["Id"].(string)
	v, err := models.GetLivechannelById(ldata.Id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	v.Vhost = ldata.Vhost
	v.Stream = ldata.Stream
	v.Title = ldata.Title
	v.Url = v.Vhost + "/" + v.Stream
	v.Remark = ldata.Remark

	// //	范围
	// scope, _ := sdata["Scope"].(string)
	v.Scope = ldata.Scope
	// vstatus, _ := sdata["Status"].(string)
	v.Status = ldata.Status
	v.Updater = user.Name
	v.Utime = time.Now()
	// //是否录制
	// vtype, _ := sdata["Type"].(sring)
	v.Type = ldata.Type

	//	设置SRS录制
	//	enableSrc := "http://" + beego.AppConfig.String("StreadmAddress") +
	//		":1985/api/v1/raw?rpc=update&scope=dvr&value=__defaultVhost__" +
	//		"&param=enable&data=" + v.Url
	//	disableSrc := "http://" + beego.AppConfig.String("StreadmAddress") +
	//		":1985/api/v1/raw?rpc=update&scope=dvr&value=__defaultVhost__" +
	//		"&param=disable&data=" + v.Url
	//	//默认不录制
	//	req := httplib.Get(disableSrc)
	//	if v.Type == 1 {
	//		req = httplib.Get(enableSrc)
	//	}
	//	result := new(map[string]interface{})
	//	_, err = req.Response()
	//	if err != nil {
	//		c.RetError(ErrWriteFile)
	//	}
	//	req.ToJSON(&result)
	//	beego.Debug("/api/v1/raw?rpc=update:", result, err)

	v.Utime = time.Now()
	if v.Scope == 3 {
		models.DeleteUserLiveByLiveId(ldata.Id)
		// users := strings.Split(ldata.Users, ",")
		for _, e := range ldata.Users {
			// uid, _ := strconv.ParseInt(e, 10, 64)
			_, err = models.AddUserLive(e, v.Id)
			beego.Error(err)
			c.Dlog("添加了直播用户授权，id：", v.Id)
		}

	}
	err = models.UpdateLivechannelById(v)
	if err != nil {
		c.RetError(ErrDatabase)
	}

	c.Dlog("修改了直播频道信息", ldata.Id)
	c.RetSuccess(ldata.Id)
}

// @Title Delete
// @Description delete the Livechannel
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *LivechannelController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	if err != nil {
		c.RetError(ErrInputData)
	}
	if err := models.SoftDeleteLivechannel(id, user.Name); err == nil {
		c.Dlog("删除了直播频道信息", id)
		c.RetSuccess(id)
	}
	c.RetError(ErrDatabase)
}

// @Title DeleteLiveChannels
// @Description DeleteLiveChannels
// @Success 200 {string} DeleteLiveChannels success!
// @Failure 403
// @router /DeleteLiveChannels [post]
func (c *LivechannelController) DeleteLiveChannels() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		id := value.(string)
		err := models.SoftDeleteLivechannel(id, user.Name)
		if err != nil {
			c.RetError(ErrDatabase)
		}
		c.Dlog("删除了直播频道", id)

	}
	c.RetSuccess(sdata)
}

// @Title 获取直播列表
// @Description 获取直播列表
// @Success GetLiveList success!
// @Failure
// @router /GetLiveList [get]
func (c *LivechannelController) GetLiveList() {
	//	var query map[string]string = make(map[string]string)
	user := c.User
	//用户角色不是系统管理员的筛选单位
	var l []interface{}
	var err error
	if user.Role[0].Type > 0 {
		l, err = models.GetChannelListByOrg(user)
	} else {
		l, _, err = models.GetChannelList()
	}
	if err != nil {
		c.RetError(ErrNoData)
	}
	//	beego.Debug(l)
	c.RetSuccess(l)
}

// @Title 获取直播频道的人员授权
// @Description 获取直播频道的人员授权
// @Success GetLiveUserByLive success!
// @Failure
// @router /GetLiveUserByLive/:id [get]
func (c *LivechannelController) GetLiveUserByLive() {
	id := c.GetString(":id")
	// id := c.Ctx.Input.Param(":id")
	beego.Debug(id)
	live, err := models.GetLivechannelById(id)
	if err != nil {
		c.RetError(ErrPermission)
	}
	var users []string
	for _, v := range live.User {
		users = append(users, v.Id)
	}
	c.RetSuccess(users)
}

// @Title LiveList
// @Description 获取直播列表分页
// @Success LiveList success!
// @Failure
// @router /LiveList [post]
func (c *LivechannelController) LiveList() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	CurrentPageIndex := sdata["CurrentPageIndex"].(string)
	PageSize := sdata["PageSize"].(string)
	pageindex, _ := strconv.Atoi(CurrentPageIndex)
	pagesize, _ := strconv.Atoi(PageSize)
	//	log.Debug("1111111111:", CurrentPageIndex, PageSize)
	var l []interface{}
	var cl int64
	if user.Role[0].Type > 0 {
		l, err = models.GetChannelListByOrg(user)
	} else {
		l, _, err = models.GetChannelList()
	}
	if err != nil {
		beego.Error(err)
		c.RetError(ErrNoData)
	}
	if err != nil {
		beego.Error(err)
		c.RetError(ErrNoData)
	}
	beego.Debug((pageindex-1)*pagesize, pagesize)
	beego.Debug(cl)
	beego.Debug(user.Role[0].Type)
	if len(l) < (pageindex-1)*pagesize {
		beego.Error(err)
		c.RetError(ErrNoData)
	} else {
		if len(l) > (pageindex)*pagesize {
			c.RetSuccess(l[(pageindex-1)*pagesize : pagesize])
		} else {
			c.RetSuccess(l[(pageindex-1)*pagesize:])
		}

	}

}
